<?php
namespace app\admin\controller\customer;

use app\admin\model\Customer;
use app\common\controller\Backend;
use think\Db;
use think\Exception;

class Index extends Backend
{
    protected $model = null;
    protected $noNeedRight = [];
        protected $searchFields = ['name'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new Customer();
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            $mimetypeQuery = [];
            $filter = $this->request->request('filter');
            $filterArr = (array)json_decode($filter, true);
            $this->request->get(['filter' => json_encode($filterArr)]);


            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $whereNew = [
                'is_delete' => 0
            ];
            $list = $this->model
                ->where($mimetypeQuery)
                ->where($where)
                ->where($whereNew)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $subData = $this->request->param();
            $subData['row']['admin_id'] = $this->auth->id;

            try {
                Db::startTrans();
                $this->model->allowField(true)->save($subData['row']);

            }catch (Exception $exception) {
                Db::rollback();
                $this->error('提交失败：'.$exception->getMessage());
            }
            Db::commit();
            $this->success(' 提交成功');
        }


        return $this->view->fetch();
    }

    public function edit($ids = "")
    {
        if ($this->request->isAjax()) {
            $subData = $this->request->param();

            try {
                $model = $this->model->find($ids);
                $model->allowField(true)->save($subData['row']);

            }catch (Exception $exception) {
                Db::rollback();
                $this->error('提交失败：'.$exception->getMessage());
            }
            Db::commit();
            $this->success('修改成功');
        }

        $detail = $this->model->find($ids);
        $this->assign('detail', $detail);

        return $this->view->fetch();
    }


    // 详情
    public function detail($ids = '')
    {
        $detail = $this->model->find($ids);
        $detail['createtime'] = date('Y-m-d H:i:s', $detail['createtime']);

        $this->assign('order', $detail);

        return $this->view->fetch();
    }

}
